#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <locale.h>
#include <ncurses.h>
#include "client.h"
#include "../common/common.h"
#include "../common/protocol.h"
#include "../ui/ui.h"
#include "../chess_logic/chess_logic.h"

#define SERVER_IP "127.0.0.1"
#define PORT 8888

int server_socket;
User current_user;
bool connected_to_server = false;

bool connect_to_server() {
	struct sockaddr_in server_addr;

	server_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (server_socket < 0) {
		return false;
	}

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(PORT);
	server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

	if (connect(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
		return false;
	}

	connected_to_server = true;
	return true;
}

void login_screen() {
	if (!connected_to_server) {
		if (!connect_to_server()) {
			printw("Failed to connect to server!\n");
			printw("Press any key to continue...");
			getch();
			return;
		}
	}

	char username[32], password[32];

	clear();
	printw("=== Chess Game Login ===\n\n");
	printw("Username: ");
	echo();
	getstr(username);
	noecho();
	printw("Password: ");
	echo();
	getstr(password);
	noecho();

	Message msg;
	msg.type = MSG_LOGIN;
	snprintf(msg.data, sizeof(msg.data), "%s:%s", username, password);

	send_message(server_socket, &msg);

	// 等待服务器响应
	if (receive_message(server_socket, &msg) > 0) {
		if (msg.type == MSG_ERROR) {
			printw("Login failed: %s\n", msg.data);
			printw("Press any key to continue...");
			getch();
			login_screen();
		} else {
			// 解析用户信息
			sscanf(msg.data, "%d:%s:%d", &current_user.id, current_user.username, &current_user.elo_rating);
			current_user.is_online = true;
			main_menu();
		}
	}
}

void register_screen() {
	if (!connected_to_server) {
		if (!connect_to_server()) {
			printw("Failed to connect to server!\n");
			printw("Press any key to continue...");
			getch();
			return;
		}
	}

	char username[32], password[32], confirm_password[32];

	clear();
	printw("=== Chess Game Registration ===\n\n");
	printw("Username: ");
	echo();
	getstr(username);
	noecho();
	printw("Password: ");
	echo();
	getstr(password);
	noecho();
	printw("Confirm Password: ");
	echo();
	getstr(confirm_password);
	noecho();

	if (strcmp(password, confirm_password) != 0) {
		printw("Passwords do not match!\n");
		printw("Press any key to continue...");
		getch();
		register_screen();
		return;
	}

	Message msg;
	msg.type = MSG_REGISTER;
	snprintf(msg.data, sizeof(msg.data), "%s:%s", username, password);

	send_message(server_socket, &msg);

	// 等待服务器响应
	if (receive_message(server_socket, &msg) > 0) {
		if (msg.type == MSG_ERROR) {
			printw("Registration failed: %s\n", msg.data);
		} else {
			printw("Registration successful! Please login.\n");
		}
		printw("Press any key to continue...");
		getch();
		login_screen();
	}
}

// 单机AI对局函数
void offline_ai_game() {
	ChessGame game;
	initialize_board(game.board);
	game.white_to_move = true;
	game.white_can_castle_kingside = true;
	game.white_can_castle_queenside = true;
	game.black_can_castle_kingside = true;
	game.black_can_castle_queenside = true;
	game.en_passant_target = -1;
	game.halfmove_clock = 0;
	game.fullmove_number = 1;
	game.pending_promotion = false;
	game.promote_row = -1;
	game.promote_col = -1;
	game.white_in_check = false;
	game.black_in_check = false;
	game.game_over = false;
	game.winner = ' ';
	game.player_is_white = true;
	game.ai_thinking = false;
	game.ai_difficulty = 2;

	// 初始化随机数生成器
	srand(time(NULL));

	// 游戏主循环
	bool quit = false;
	int selected_row = -1, selected_col = -1;

	// 初始将军状态
	update_check_status(&game);

	while (!quit && !game.game_over) {
		draw_chess_board(&game);

		// 显示当前难度
		printw("AI Difficulty: ");
		switch (game.ai_difficulty) {
			case 1: printw("Easy"); break;
			case 2: printw("Medium"); break;
			case 3: printw("Hard"); break;
		}
		printw("\n");

		// AI回合
		if (!game.pending_promotion) {
			bool player_turn = (game.player_is_white && game.white_to_move) || 
				(!game.player_is_white && !game.white_to_move);

			if (!player_turn) {
				ai_move(&game);
				continue;
			}
		}

		// 处理兵升变
		if (game.pending_promotion) {
			printw("\nPromote pawn to: (Q)ueen, (R)ook, (B)ishop, k(N)ight: ");
			refresh();

			int ch = getch();
			char new_piece;
			switch (toupper(ch)) {
				case 'Q': 
					new_piece = game.white_to_move ? WHITE_QUEEN : BLACK_QUEEN;
					break;
				case 'R': 
					new_piece = game.white_to_move ? WHITE_ROOK : BLACK_ROOK;
					break;
				case 'B': 
					new_piece = game.white_to_move ? WHITE_BISHOP : BLACK_BISHOP;
					break;
				case 'N': 
					new_piece = game.white_to_move ? WHITE_KNIGHT : BLACK_KNIGHT;
					break;
				default: 
					continue; // 无效输入，重新等待
			}

			// 执行升变
			game.board[game.promote_row][game.promote_col] = new_piece;
			game.pending_promotion = false;
			game.promote_row = -1;
			game.promote_col = -1;

			// 切换玩家
			game.white_to_move = !game.white_to_move;
			if (!game.white_to_move) {
				game.fullmove_number++;
			}

			// 更新将军状态
			update_check_status(&game);

			// 检查游戏是否结束
			check_game_over(&game);

			continue; // 重新绘制棋盘
		}

		int ch = getch();
		switch (ch) {
			case 'q': // 退出
				quit = true;
				break;

			case 's': // 切换执方
				game.player_is_white = !game.player_is_white;
				break;

			case 'd': // 改变AI难度
				game.ai_difficulty = (game.ai_difficulty % 3) + 1;
				break;

			case KEY_MOUSE: // 鼠标选择
				{
					MEVENT event;
					if (getmouse(&event) == OK) {
						// 计算棋盘坐标
						int row = event.y - 2;
						int col = (event.x - 3) / 2;

						if (row >= 0 && row < 8 && col >= 0 && col < 8) {
							if (selected_row == -1) {
								// 选择棋子
								char piece = game.board[row][col];
								if (piece != EMPTY) {
									bool is_player_piece = (game.player_is_white && isupper(piece)) ||
										(!game.player_is_white && islower(piece));

									if (is_player_piece) {
										selected_row = row;
										selected_col = col;
									}
								}
							} else {
								// 尝试移动
								if (is_move_valid(&game, selected_row, selected_col, row, col)) {
									make_move(&game, selected_row, selected_col, row, col);
								}
								selected_row = -1;
								selected_col = -1;
							}
						}
					}
				}
				break;
		}
	}

	// 游戏结束处理
	if (game.game_over) {
		draw_chess_board(&game);
		printw("Game Over! ");
		if (game.winner == 'W') {
			printw("White wins!\n");
		} else if (game.winner == 'B') {
			printw("Black wins!\n");
		} else {
			printw("Draw!\n");
		}
		printw("Press any key to continue...");
		getch();
	}
}

void online_players_screen() {
	// 请求在线玩家列表
	Message msg;
	msg.type = MSG_GET_ONLINE_USERS;
	send_message(server_socket, &msg);

	// 接收在线玩家列表
	if (receive_message(server_socket, &msg) > 0 && msg.type != MSG_ERROR) {
		// 解析玩家列表
		// 格式: id:username:elo;id:username:elo;...
		clear();
		printw("=== Online Players ===\n\n");

		char *token = strtok(msg.data, ";");
		int index = 1;
		User users[50];
		int user_count = 0;

		while (token != NULL && user_count < 50) {
			sscanf(token, "%d:%[^:]:%d", 
					&users[user_count].id, 
					users[user_count].username, 
					&users[user_count].elo_rating);

			// 不显示自己
			if (users[user_count].id != current_user.id) {
				printw("%d. %s (ELO: %d)\n", index, users[user_count].username, users[user_count].elo_rating);
				index++;
			}

			token = strtok(NULL, ";");
			user_count++;
		}

		if (index == 1) {
			printw("No other players online.\n");
			printw("Press any key to continue...");
			getch();
			return;
		}

		printw("\nEnter player number to challenge (0 to go back): ");
		echo();
		int choice;
		scanw("%d", &choice);
		noecho();

		if (choice > 0 && choice < index) {
			// 找到选中的玩家
			User selected_user;
			int selected_elo = 0; // 添加这个变量来保存对手的ELO
			int selected_index = 0;
			for (int i = 0; i < user_count; i++) {
				if (users[i].id != current_user.id) {
					selected_index++;
					if (selected_index == choice) {
						selected_user = users[i];
						selected_elo = users[i].elo_rating; // 保存对手的ELO
						break;
					}
				}
			}

			// 向选中的玩家发送游戏请求
			Message challenge_msg;
			challenge_msg.type = MSG_REQUEST_GAME;
			challenge_msg.to_user_id = selected_user.id;
			challenge_msg.from_user_id = current_user.id; // 设置发送者ID
			snprintf(challenge_msg.data, sizeof(challenge_msg.data), "Game request from %s", current_user.username);

			send_message(server_socket, &challenge_msg);

			printw("\nChallenge sent to %s. Waiting for response...\n", selected_user.username);
			printw("Press 'q' to cancel\n");
			refresh();

			// 等待响应，允许用户取消
			bool waiting = true;
			nodelay(stdscr, TRUE); // 设置非阻塞输入

			while (waiting) {
				// 设置socket为非阻塞模式
				int flags = fcntl(server_socket, F_GETFL, 0);
				fcntl(server_socket, F_SETFL, flags | O_NONBLOCK);

				// 检查是否有响应
				if (receive_message(server_socket, &msg) > 0) {
					if (msg.type == MSG_RESPOND_GAME) {
						if (strcmp(msg.data, "accept") == 0) {
							printw("\nAccepted! Starting game...\n");
							refresh();
							sleep(2);

							// 等待游戏开始消息
							Message start_msg;
							if (receive_message(server_socket, &start_msg) > 0 && start_msg.type == MSG_GAME_START) {
								char side;
								int opponent_id;
								sscanf(start_msg.data, "%c:%d", &side, &opponent_id);

								bool is_white = (side == 'W');
								start_pvp_game(selected_user.id, selected_user.username, selected_elo, is_white);
							}
							waiting = false;
						} else if (strcmp(msg.data, "decline") == 0) {
							printw("\nChallenge was declined.\n");
							printw("Press any key to continue...");
							refresh();
							waiting = false;
						} else if (strcmp(msg.data, "cancel") == 0) {
							printw("\nChallenge was cancelled by the opponent.\n");
							printw("Press any key to continue...");
							refresh();
							waiting = false;
						}
					}
				}

				// 恢复socket为阻塞模式
				fcntl(server_socket, F_SETFL, flags);

				// 检查用户是否取消
				int ch = getch();
				if (ch != ERR) {
					if (ch == 'q') {
						// 发送取消请求
						Message cancel_msg;
						cancel_msg.type = MSG_CANCEL_GAME;
						cancel_msg.to_user_id = selected_user.id;
						cancel_msg.from_user_id = current_user.id;
						send_message(server_socket, &cancel_msg);

						printw("Challenge cancelled.\n");
						waiting = false;
					}
				}

				// 短暂休眠，避免CPU占用过高
				usleep(100000); // 100ms
			}
			nodelay(stdscr, FALSE);
			printw("Press any key to continue...");
			getch();
		}
	} else {
		printw("Error retrieving online players.\n");
		printw("Press any key to continue...");
		getch();
	}
}

// 修改 client.c 中的 start_pvp_game 函数
void start_pvp_game(int opponent_id, char *opponent_name, int opponent_elo, bool is_white) {
	// 创建游戏状态
	ChessGame game;
	initialize_board(game.board);
	game.white_to_move = true;
	game.white_can_castle_kingside = true;
	game.white_can_castle_queenside = true;
	game.black_can_castle_kingside = true;
	game.black_can_castle_queenside = true;
	game.en_passant_target = -1;
	game.halfmove_clock = 0;
	game.fullmove_number = 1;
	game.pending_promotion = false;
	game.promote_row = -1;
	game.promote_col = -1;
	game.white_in_check = false;
	game.black_in_check = false;
	game.game_over = false;
	game.winner = ' ';
	game.player_is_white = is_white;  // 使用传入的执方参数，而不是固定为true
	game.ai_thinking = false;
	game.ai_difficulty = 2;

	// 存储对手信息
	game.opponent_id = opponent_id;
	strncpy(game.opponent_name, opponent_name, sizeof(game.opponent_name) - 1);
	game.opponent_elo = opponent_elo;

	// 游戏循环
	game_loop(&game, false, opponent_id); // false表示是PVP游戏
}

// 修改 client.c 中的 game_loop 函数
void game_loop(ChessGame *game, bool is_ai_game, int opponent_id) {
    // 游戏主循环
    bool quit = false;
    int selected_row = -1, selected_col = -1;

    // 初始将军状态
    update_check_status(game);

    // 添加一个标志来控制是否需要重绘棋盘
    bool need_redraw = true;

    while (!quit && !game->game_over) {
        // 只有在需要时才重绘棋盘
        if (need_redraw) {
            draw_chess_board(game);
            need_redraw = false;
        }

        // 显示游戏模式 - 修复显示问题
        if (is_ai_game) {
            printw("Mode: %s\n", game->player_is_white ? 
                    "Player(White) vs AI(Black)" : "Player(Black) vs AI(White)");
        } else {
            // 显示对手信息
            printw("Mode: Online PVP (vs %s:%d)\n", game->opponent_name, game->opponent_elo);
        }

        // AI回合
        if (is_ai_game && !game->pending_promotion) {
            bool player_turn = (game->player_is_white && game->white_to_move) || 
                (!game->player_is_white && !game->white_to_move);

            if (!player_turn) {
                ai_move(game);
                need_redraw = true; // AI移动后需要重绘
                continue;
            }
        }

        // 处理兵升变
        if (game->pending_promotion) {
            printw("\nPromote pawn to: (Q)ueen, (R)ook, (B)ishop, k(N)ight: ");
            refresh();

            int ch = getch();
            char new_piece;
            switch (toupper(ch)) {
                case 'Q': 
                    new_piece = game->white_to_move ? WHITE_QUEEN : BLACK_QUEEN;
                    break;
                case 'R': 
                    new_piece = game->white_to_move ? WHITE_ROOK : BLACK_ROOK;
                    break;
                case 'B': 
                    new_piece = game->white_to_move ? WHITE_BISHOP : BLACK_BISHOP;
                    break;
                case 'N': 
                    new_piece = game->white_to_move ? WHITE_KNIGHT : BLACK_KNIGHT;
                    break;
                default: 
                    continue; // 无效输入，重新等待
            }

            // 执行升变
            game->board[game->promote_row][game->promote_col] = new_piece;
            game->pending_promotion = false;
            game->promote_row = -1;
            game->promote_col = -1;

            // 切换玩家
            game->white_to_move = !game->white_to_move;
            if (!game->white_to_move) {
                game->fullmove_number++;
            }

            // 更新将军状态
            update_check_status(game);

            // 检查游戏是否结束
            check_game_over(game);

            // 如果是PVP游戏，发送升变信息给对手
            if (!is_ai_game) {
                Message promote_msg;
                promote_msg.type = MSG_PROMOTION;
                promote_msg.to_user_id = opponent_id;
                promote_msg.from_user_id = current_user.id;
                // 数据格式: "row:col:piece"
                snprintf(promote_msg.data, sizeof(promote_msg.data), "%d:%d:%c", 
                         game->promote_row, game->promote_col, new_piece);
                send_message(server_socket, &promote_msg);
            }

            need_redraw = true; // 升变后需要重绘
            continue; // 重新绘制棋盘
        }

        // PVP游戏：检查是否有来自对手的移动
        if (!is_ai_game) {
            // 设置socket为非阻塞模式
            int flags = fcntl(server_socket, F_GETFL, 0);
            fcntl(server_socket, F_SETFL, flags | O_NONBLOCK);

            Message msg;
            if (receive_message(server_socket, &msg) > 0) {
                if (msg.type == MSG_MOVE) {
                    // 解析对手的移动
                    int from_row, from_col, to_row, to_col;
                    char promotion_piece;
                    sscanf(msg.data, "%d:%d:%d:%d:%c", &from_row, &from_col, &to_row, &to_col, &promotion_piece);

                    // 执行对手的移动
                    make_move(game, from_row, from_col, to_row, to_col);

                    // 如果有升变，设置升变信息
                    if (promotion_piece != ' ') {
                        game->promotion_piece = promotion_piece;
                    }

                    need_redraw = true; // 对手移动后需要重绘
                    continue; // 重新绘制棋盘
                } else if (msg.type == MSG_PROMOTION) {
                    // 处理对手的升变消息：直接更新棋盘
                    int row, col;
                    char promotion_piece;
                    sscanf(msg.data, "%d:%d:%c", &row, &col, &promotion_piece);
                    game->board[row][col] = promotion_piece;
                    need_redraw = true;
                    continue;
                } else if (msg.type == MSG_GAME_OVER) {
                    // 游戏结束
                    game->game_over = true;
                    if (strcmp(msg.data, "W") == 0) {
                        game->winner = 'W';
                    } else if (strcmp(msg.data, "B") == 0) {
                        game->winner = 'B';
                    } else {
                        game->winner = 'D';
                    }
                    break;
                } else if (msg.type == MSG_RESIGN) {
                    // 对手认输
                    game->game_over = true;
                    game->winner = game->player_is_white ? 'W' : 'B';
                    break;
                }
            }

            // 恢复socket为阻塞模式
            fcntl(server_socket, F_SETFL, flags);
        }

        // 设置非阻塞输入检查
        nodelay(stdscr, TRUE);
        int ch = getch();
        nodelay(stdscr, FALSE);

        if (ch != ERR) {
            switch (ch) {
                case 'q': // 退出
                    quit = true;
                    // 如果是PVP游戏，通知对手
                    if (!is_ai_game) {
                        Message resign_msg;
                        resign_msg.type = MSG_RESIGN;
                        resign_msg.to_user_id = opponent_id;
                        resign_msg.from_user_id = current_user.id;
                        send_message(server_socket, &resign_msg);
                    }
                    break;

                case 's': // 切换执方（仅AI游戏）
                    if (is_ai_game) {
                        game->player_is_white = !game->player_is_white;
                        need_redraw = true;
                    }
                    break;

                case 'd': // 改变AI难度（仅AI游戏）
                    if (is_ai_game) {
                        game->ai_difficulty = (game->ai_difficulty % 3) + 1;
                        need_redraw = true;
                    }
                    break;

                case KEY_MOUSE: // 鼠标选择
                    {
                        MEVENT event;
                        if (getmouse(&event) == OK) {
                            // 计算棋盘坐标
                            int row = event.y - 2;
                            int col = (event.x - 3) / 2;
            
                            if (row >= 0 && row < 8 && col >= 0 && col < 8) {
                                if (selected_row == -1) {
                                    // 选择棋子
                                    char piece = game->board[row][col];
                                    if (piece != EMPTY) {
                                        bool is_player_piece = (game->player_is_white && isupper(piece)) ||
                                            (!game->player_is_white && islower(piece));
            
                                        if (is_player_piece) {
                                            selected_row = row;
                                            selected_col = col;
                                            need_redraw = true; // 选择棋子后需要重绘以显示高亮
                                        }
                                    }
                                } else {
                                    // 尝试移动
                                    if (is_move_valid(game, selected_row, selected_col, row, col)) {
                                        make_move(game, selected_row, selected_col, row, col);
                                        need_redraw = true; // 移动后需要重绘
            
                                        // 如果是PVP游戏，发送移动信息给对手
                                        if (!is_ai_game) {
                                            Message move_msg;
                                            move_msg.type = MSG_MOVE;
                                            move_msg.to_user_id = opponent_id;
                                            move_msg.from_user_id = current_user.id;
            
                                            // 获取升变棋子（如果有）
                                            char promo_piece = ' ';
                                            if (game->pending_promotion) {
                                                // 这里应该根据用户选择的升变棋子来设置
                                                // 但在移动时还不知道用户会选择什么，所以先发送移动，升变单独处理
                                                promo_piece = ' '; // 先设置为空，升变会单独发送消息
                                            }
            
                                            snprintf(move_msg.data, sizeof(move_msg.data), 
                                                    "%d:%d:%d:%d:%c", 
                                                    selected_row, 
                                                    selected_col, 
                                                    row,
                                                    col,
                                                    promo_piece);
            
                                            send_message(server_socket, &move_msg);
                                        }
                                    }
                                    selected_row = -1;
                                    selected_col = -1;
                                    need_redraw = true; // 取消选择后需要重绘
                                }
                            }
                        }
                    }
                    break;
            }
        } else {
            // 没有输入时，短暂休眠以减少CPU使用
            napms(50); // 休眠50毫秒
        }

        // 检查游戏结束条件
        update_check_status(game);
        check_game_over(game);

        // 如果是PVP游戏且游戏结束，通知对手
        if (!is_ai_game && game->game_over) {
            Message game_over_msg;
            game_over_msg.type = MSG_GAME_OVER;
            game_over_msg.to_user_id = opponent_id;
            snprintf(game_over_msg.data, sizeof(game_over_msg.data), "%c", game->winner);
            send_message(server_socket, &game_over_msg);
        }
    }

    // 游戏结束处理
    draw_chess_board(game);
    printw("Game Over! ");
    if (game->winner == 'W') {
        printw("White wins!\n");
    } else if (game->winner == 'B') {
        printw("Black wins!\n");
    } else {
        printw("Draw!\n");
    }
    printw("Press any key to continue...");
    refresh();
    getch();
}

void main_menu() {
	int choice = 0;
	while (1) {
		// 非阻塞检查消息
		int flags = fcntl(server_socket, F_GETFL, 0);
		fcntl(server_socket, F_SETFL, flags | O_NONBLOCK);

		Message msg;
		if (receive_message(server_socket, &msg) > 0) {
			// 处理游戏请求
			if (msg.type == MSG_REQUEST_GAME) {
				// 恢复阻塞模式
				fcntl(server_socket, F_SETFL, flags);

				// 解析对手信息
				char opponent_name[32];
				int opponent_elo = 0;
				sscanf(msg.data, "Game request from %s", opponent_name);

				// 显示挑战请求提示
				clear();
				printw("=== Game Request ===\n\n");
				printw("You have a game request from: %s\n", opponent_name);
				printw("Do you want to accept? (y/n): ");
				refresh();

				// 等待用户输入
				int ch = getch();
				if (ch == 'y' || ch == 'Y') {
					// 接受挑战
					Message response;
					response.type = MSG_RESPOND_GAME;
					response.to_user_id = msg.from_user_id;
					response.from_user_id = current_user.id;
					strcpy(response.data, "accept");
					send_message(server_socket, &response);

					// 等待游戏开始消息
					Message start_msg;
					if (receive_message(server_socket, &start_msg) > 0 && start_msg.type == MSG_GAME_START) {
						char side;
						int opponent_id;
						sscanf(start_msg.data, "%c:%d", &side, &opponent_id);

						// 开始PVP游戏
						printw("\nAccepted! Starting game...\n");
						refresh();
						sleep(2);
						bool is_white = (side == 'W');
						start_pvp_game(opponent_id, opponent_name, 1200, is_white); // 默认ELO为1200，实际应从数据库获取
					}
				} else {
					// 拒绝挑战
					Message response;
					response.type = MSG_RESPOND_GAME;
					response.to_user_id = msg.from_user_id;
					response.from_user_id = current_user.id;
					strcpy(response.data, "decline");
					send_message(server_socket, &response);

					printw("\nDeclined.\n");
					printw("Press any key to continue...");
					getch();
				}
				continue; // 返回主菜单
			}

			// 处理游戏开始消息
			if (msg.type == MSG_GAME_START) {
				// 恢复阻塞模式
				fcntl(server_socket, F_SETFL, flags);

				// 解析游戏开始消息
				char side;
				int opponent_id;
				sscanf(msg.data, "%c:%d", &side, &opponent_id);

				// 查找对手信息
				User opponent;
				// 这里需要从服务器获取对手信息，或者从之前存储的列表中查找
				// 假设我们已经有了对手信息

				// 开始游戏
				bool is_white = (side == 'W');
				start_pvp_game(opponent_id, "Opponent", 1200, is_white); // 使用默认值，实际应从数据库获取
				continue;
			}
		}

		// 恢复阻塞模式
		fcntl(server_socket, F_SETFL, flags);

		// 正常绘制主菜单
		clear();
		printw("=== Main Menu ===\n\n");
		if (connected_to_server && current_user.id != 0) {
			printw("Welcome, %s (ELO: %d)\n\n", current_user.username, current_user.elo_rating);
		} else {
			printw("Welcome to Chess Game\n\n");
		}

		printw("1. Play vs AI (Offline)\n");

		if (connected_to_server && current_user.id != 0) {
			printw("2. Play Online (vs Players)\n");
			printw("3. Logout\n");
			printw("4. Exit\n");
		} else if (connected_to_server) {
			printw("2. Login/Register\n");
			printw("3. Disconnect from Server\n");
			printw("4. Exit\n");
		} else {
			printw("2. Connect to Server\n");
			printw("3. Exit\n");
		}

		printw("\nChoice: ");
		choice = getch() - '0';

		switch (choice) {
			case 1:
				offline_ai_game();
				break;
			case 2:
				if (connected_to_server && current_user.id != 0) {
					online_players_screen();
				} else if (connected_to_server) {
					int auth_choice = 0;
					while (auth_choice != 3) {
						clear();
						printw("=== Chess Game ===\n\n");
						printw("1. Login\n");
						printw("2. Register\n");
						printw("3. Back to Main Menu\n\n");
						printw("Choice: ");

						auth_choice = getch() - '0';

						switch (auth_choice) {
							case 1:
								login_screen();
								break;
							case 2:
								register_screen();
								break;
							case 3:
								break;
						}
					}
				} else {
					if (connect_to_server()) {
						printw("Connected to server!\n");
						printw("Press any key to continue...");
						getch();
					} else {
						printw("Failed to connect to server!\n");
						printw("Press any key to continue...");
						getch();
					}
				}
				break;
			case 3:
				if (connected_to_server && current_user.id != 0) {
					logout();
					return;
				} else if (connected_to_server) {
					close(server_socket);
					connected_to_server = false;
					printw("Disconnected from server.\n");
					printw("Press any key to continue...");
					getch();
				} else {
					exit(0);
				}
				break;
			case 4:
				if (connected_to_server && current_user.id != 0) {
					exit(0);
				}
				break;
		}
	}
}

void logout() {
	if (connected_to_server) {
		Message msg;
		msg.type = MSG_LOGOUT;
		send_message(server_socket, &msg);

		// 重置当前用户
		memset(&current_user, 0, sizeof(User));
	}

	// 返回主菜单
	main_menu();
}

int main() {
	setlocale(LC_ALL, "en_US.UTF-8");
	initscr();
	cbreak();
	noecho();
	keypad(stdscr, TRUE);
	mousemask(ALL_MOUSE_EVENTS, NULL);
	curs_set(0);

	// 初始化颜色
	if (has_colors()) {
		start_color();
		init_pair(1, COLOR_WHITE, COLOR_BLUE);    // 浅色格子
		init_pair(2, COLOR_BLACK, COLOR_CYAN);    // 深色格子
	}

	// 直接进入主菜单，不强制连接服务器
	main_menu();

	close(server_socket);
	endwin();
	return 0;
}
